const Sequelize = require('sequelize');

module.exports = function (sequelize, DataTypes) {
  const Articles = sequelize.define('Articles', {
    id: {
      autoIncrement: true,
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      primaryKey: true
    },
    classId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: "分类id"
    },
    title: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "标题"
    },
    content: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: "内容"
    },
    image_url: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "图片地址"
    },
    publisher_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: "发布人id"
    },
    status: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "发布状态0编辑1发布2删除"
    },
    likesCount: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: "点赞量"
    },
    collect: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "收藏量"
    },
    sort_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: "分类id"
    }
  }, {
    sequelize,
    tableName: 'Articles',
    timestamps: true,
    indexes: [
      {
        name: "PRIMARY",
        unique: true,
        using: "BTREE",
        fields: [
          { name: "id" },
        ]
      },
    ]
  });

  Articles.associate = function (models) {
    Articles.belongsToMany(models.Users, {
      through: models.Likes,
      foreignKey: 'postid', // 将 Likes 表中的 postid 字段与 Articles 表关联
      otherKey: 'userid', // 将 Likes 表中的 userid 字段与 Users 表关联
      as: 'likeUsers'
    });
    Articles.belongsTo(models.Users, {
      foreignKey: 'publisher_id', // 指定 Articles 表中用来关联的字段
      targetKey: 'id', // 指定 Users 表中被关联的字段
      as: 'publisher' // 别名定义为 'publisher'
    });
  };

  return Articles;
};
